﻿

using System.Drawing;
using System.IO;

using OpenCvSharp;

using PaddleOCRSharp;

using Xc.DataAccess.CodeReader.Properties;
using Xc.DataAccess.Core;

namespace Xc.DataAccess.CodeReader.Models.Filters
{
    [Filter("OCR识别", FilterType.Algorithm)]
    public class AlgorithmOcrTextDetect : FilterBase
    {
        private OCRResult oCRResult;

        [OutputParameter("识别结果")]
        public OCRResult OCRResult
        {
            get => oCRResult; private set
            {
                oCRResult = value;
                RaisedPropertyChanged();
            }
        }
        private PaddleOCRSharp.PaddleOCREngine paddle;
        internal override ResultData<Mat> UseChannel(Mat mat, FilterBase[] filterInfos, FilterBase preFilterBase)
        {
            if (paddle==null)
            {
                OCRParameter oCRParameter = new OCRParameter();

                paddle = new PaddleOCRSharp.PaddleOCREngine(null, oCRParameter);
            }
            try
            {
                using (var stream = mat.ToMemoryStream())
                {
                    using (var bitmap = new Bitmap(stream))
                    {
                        var c = paddle.DetectText(bitmap);
                        if (c != null && !string.IsNullOrEmpty(c.Text))
                        {
                            OCRResult = c;
                        }
                        return ResultData<Mat>.Accept(TextResource.filter_action_complete, mat);
                    }
                }
            }
            catch (System.Exception err)
            {
               return ResultData<Mat>.Reject(err.Message,null);
            }



        }
    }

}
